package com.ns.core.utils.rsa;


import org.apache.tomcat.util.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA公钥/私钥/签名工具包
 *
 * @author liao.wei
 * @since 2022/6/13
 */
public class RsaUtil {
    public static final String PRIVATE_KEY_STRING = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+vB8ji8Od19y6VBssY8vOQPKXkzY9NUGQs/dmTXMyJ2f8IvdVzScOzSzTAYuuQErwQ5+eL4tbiUJ5VRrH515ow4TBGjju6zxO7qX8W6qt8IjkR/AsJLLUG3CGNbpqjJEG+Wd4hm7ePJVfC95I8hzX0/HmAvCquYDn5O7uW/4l4M/9fhbT5v9dXlSev/DJVtD9//ypmOkFn7AddeoWwWYMpo2Y+7CKS10t0ovdXgs7zWAV1g01jlg54kU+LTZO47s5pV7Z+pM1ruoFsU5yvYo9iu/5Z/ZUNN2RdrVi4vYBWijlRCY3x2sPmxkMYAOuD9PMQNVTzqYDYO1y76p7IrujAgMBAAECggEAL61ao0oGheg1lqX7fOcdRNtbSKRVxIsRbpht2Ta2+ux6w74B0YLMppiHAd+7CL2tfc2JksMTtLfk0+uAHEQrh0iIYLSrUp2en6Rr/V70lTIxJc8NrBsoUHjjccjwZj3o6rNhN/FyuT6vn+iZkeZja1fhebt2aVahcFX7m72HE/RlfaC7jd2vk9nyeJW6fnxPzKt+ThW3l/aE21jgNlY360w16d40aQ5EZNeh6UDO5o4k8R2hXRpTA0LheLrFXURN4k/Rw72Hxf2DdVLq7JpnbTxEu8ukOhy3RgxpJcI9BEMakua6P1s1OQbbkRqXhpaqRJnGWr47oPPivtVzncWBIQKBgQDujQqBhwRIS5bUTS4+LaiIpTmw1NWKicHsIMcipPuQdBtVkEF2B9Qhi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+b/XV5Unr/wyVbQ/f/8qZjpBZ+wHXXqFsFmDKaNmPuwiktdLdKL3V4LO81gFdYNNY5YOeJFPi02TuO7OaVe2fqTNa7qBbFOcr2KPYrv+Wf2VDTdkXa1YuL2AVoo5UQmN8drD5sZDGADrg/TzEDVU86mA2Dtcu+qeyK7owIDAQAB";
    /**
     * RSA_ALGORITHM
     */
    private static final String RSA_ALGORITHM = "RSA";

    /**
     * 获取RSA公钥
     *
     * @param publicKey 公钥
     * @return RSAPublicKey
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    }

    /**
     * getPrivateKey
     *
     * @param privateKey 密钥字符串（经过base64编码）
     * @return RSAPrivateKey
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    }
}